import os

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
# from PyQt5.QtWebKitWidgets import *
import oss2
import sys


class MainWindow(QMainWindow):
    # noinspection PyUnresolvedReferences
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.openfile_name = ''
        # 设置窗口标题
        self.setWindowTitle('图片随机软件--正式版-guoff.taobao.com')
        # 设置窗口图标
        self.setWindowIcon(QIcon('icons/penguin.png'))
        # 设置窗口大小900*600
        self.resize(900, 600)
        self.show()

        # 设置浏览器
        self.browser = QWebEngineView()
        # url = 'http://blog.csdn.net/roger_lzh'
        # 指定打开界面的 URL
        # self.browser.setUrl(QUrl(url))
        self.navigate_to_url()
        # 添加浏览器到窗口中
        self.setCentralWidget(self.browser)
        # 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        auth = oss2.Auth('XXXX', 'XXX')
        # Endpoint以杭州为例，其它Region请按实际情况填写。
        self.bucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com', 'zmttp')

        ###使用QToolBar创建导航栏，并使用QAction创建按钮
        # 添加导航栏
        navigation_bar = QToolBar('Navigation')
        # 设定图标的大小
        navigation_bar.setIconSize(QSize(16, 16))
        #添加导航栏到窗口中
        self.addToolBar(navigation_bar)

        #QAction类提供了抽象的用户界面action，这些action可以被放置在窗口部件中
        # 添加前进、后退、停止加载和刷新的按钮
        # back_button = QAction(QIcon('icons/back.png'), 'Back', self)
        next_button = QAction(QIcon('icons/wjj.png'), '图片文件夹', self)
        # stop_button = QAction(QIcon('icons/cross.png'), 'stop', self)
        reload_button = QAction(QIcon('icons/renew.png'), '随机五个', self)
        open_button = QAction(QIcon('icons/add_page.png'), '浏览器打开', self)

        # back_button.triggered.connect(self.browser.back)
        # next_button.triggered.connect(self.browser.forward)
        next_button.triggered.connect(self.openfile)
        # stop_button.triggered.connect(self.browser.stop)
        reload_button.triggered.connect(self.reload)
        open_button.triggered.connect(self.open)

        # 将按钮添加到导航栏上
        # navigation_bar.addAction(back_button)
        navigation_bar.addAction(next_button)
        # navigation_bar.addAction(stop_button)
        navigation_bar.addAction(reload_button)
        navigation_bar.addAction(open_button)

        #添加URL地址栏
        # self.urlbar = QLineEdit()
        # # 让地址栏能响应回车按键信号
        # self.urlbar.returnPressed.connect(self.navigate_to_url)

        # navigation_bar.addSeparator()
        # navigation_bar.addWidget(self.urlbar)

        #让浏览器相应url地址的变化
        # self.browser.urlChanged.connect(self.renew_urlbar)

    def navigate_to_url(self):
        # q = QUrl(self.urlbar.text())
        # if q.scheme() == '':
        #     q.setScheme('http')
        # self.browser.setUrl(q)
        url = QUrl(QFileInfo("./pre.html").absoluteFilePath())
        self.browser.load(url)
    def open(self):
        import webbrowser
        webbrowser.open("pre.html")

    def reload(self):
        # print('随机五个',self.openfile_name)
        if self.openfile_name == '':
            reply = QMessageBox.information(self, '提示', '请先选择图片文件夹!',  QMessageBox.Close,
                                            QMessageBox.Close)
            # if reply == QMessageBox.Ok:
            #     self.la.setText('你选择了Ok！')
            # else:
            #     self.la.setText('你选择了Close！')
        else:
            #查看文件下图片数量
            count = 0
            filelist = os.listdir(self.openfile_name)
            for fn in filelist:  # fn 表示的是文件名
                count = count + 1
            # print('count',count)
            # random.choices(range(14), k=5)
            import random
            a = range(count)
            # print(random.sample(a, 5))
            randomlist = random.sample(a, 5)
            randompiclist =[]
            htmlstr = ''
            for i in randomlist:
                randompiclist.append(filelist[i])
                (shotname, extension) = os.path.splitext(filelist[i])
                picinfo = self.bucket.put_object_from_file(filelist[i], self.openfile_name+'/'+filelist[i])
                print("picinfo",picinfo)

                htmlstr = htmlstr + '''
             
                <img class="index-logo-src" src="https://zmttp.oss-cn-beijing.aliyuncs.com/'''+filelist[i]+'''" >
<p>'''+shotname+'''</p>'''
            # print(htmlstr)
            outhtml='''
            <!DOCTYPE html>
                        <html>
                        <head>
                        <meta charset="UTF-8">
                        <title>HTML5的标题</title>
                        </head>
                        <body>
         
                        '''                    +htmlstr+                        '''
                         </body>
                        </html>
                                    '''

            import datetime

            # global root
            # root.maxsize(600, 400)
            # root.minsize(300, 240)
            end_date = datetime.datetime.strptime("2099-12-24", "%Y-%m-%d")
            datetimenowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 现在
            begin_date = datetime.datetime.strptime(datetimenowTime, "%Y-%m-%d %H:%M:%S")
            print(end_date)
            print(datetimenowTime)
            print(begin_date)
            if begin_date < end_date:

                f = open('pre.html', 'w', encoding='utf-8')
                f.write(outhtml)
                f.close()

                self.navigate_to_url()
            else:
                reply = QMessageBox.information(self, '提示', '试用期已过，请联系guoff.taobao.com', QMessageBox.Close,
                                                QMessageBox.Close)
            # print(randompiclist)







    def openfile(self):
        self.openfile_name = QFileDialog.getExistingDirectory(self, '选择图片文件夹', '')
        print(self.openfile_name)

    def renew_urlbar(self, q):
        # 将当前网页的链接更新到地址栏
        self.urlbar.setText(q.toString())
        self.urlbar.setCursorPosition(0)


# 创建应用
app = QApplication(sys.argv)
# 创建主窗口
window = MainWindow()
# 显示窗口
window.show()
# 运行应用，并监听事件
app.exec_()